
#include "stdafx.h"
#include "DataArray.h"
#include "VARBinary.h"

CDataNode::CDataNode(intptr_t id, CVARBinary&data, bool copyValue) :m_id(id)
{
	if (copyValue)
		set(data.getData(), data.getLength());
	else
		Attach(data);
}
CDataNode::CDataNode(intptr_t id, LPVOID value, intptr_t length, bool copyValue) : m_id(id)
{
	if (copyValue)
		set((const byte*)value, length);
	else
		Attach((byte*)value, length);
}


CDataArray::CDataArray()
{
	count = 0; data = nullptr;
}

CDataArray::~CDataArray()
{
	clear();
}

void CDataArray::clear()
{
	if (data)
	{
		for (intptr_t i = 0; i < count; i++) if (data[i]) delete data[i];
		HeapFree(GetProcessHeap(), 0, (LPVOID)data);
	}
	count = 0; data = nullptr;
}

void CDataArray::operator =(const CDataArray& src)
{
	clear(); count = src.count; if (count <= 0) return;
	intptr_t ncount = ((count + 15) >> 4) << 4;
	data = (CDataNode**)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ncount*sizeof(CDataNode*));
	for (intptr_t i = 0; i < count; i++) if (src.data && src.data[i])
		data[i] = new CDataNode(src.data[i]->m_id, *src.data[i]);
}

intptr_t CDataArray::find(intptr_t id)
{
	for (intptr_t i = 0; i < count; i++) if (data[i] && data[i]->m_id == id) return i;
	return -1;
}

CDataNode *CDataArray::remove(intptr_t index)
{
	if (index < 0 || index >= count) return nullptr;
	CDataNode *p = data[index];
	for (intptr_t i = index; i < count - 1; i++) data[i] = data[i + 1];
	count--; data[count] = nullptr;
	return p;
}

intptr_t CDataArray::insert(intptr_t index, CDataNode *pNode)
{
	if (index < 0) index = 0;
	if (index > count) index = count;
	if ((count & 0xf) == 0)
	{
		intptr_t oldLen = count*sizeof(CDataNode *), newLen = (count + 16)*sizeof(CDataNode *);
		CDataNode **p = data; data = (CDataNode **)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, newLen);
		if (p)
		{
			memcpy_s(data, newLen, p, oldLen);
			HeapFree(GetProcessHeap(), 0, (LPVOID)p);
		}
	}
	for (intptr_t i = count; i > index; i--) data[i] = data[i - 1];
	data[index] = pNode; count++; return index;
}
